<template>
  <div class="discussion-list-container">
    <div class="discussion-header">
      <h1>讨论区</h1>
      <div class="action-buttons">
        <el-button type="primary" @click="goToCreateDiscussion" :disabled="!isLoggedIn">
          发布讨论
        </el-button>
      </div>
    </div>

    <div class="filter-options">
      <el-select v-model="sortBy" placeholder="排序字段" @change="handleFilterChange">
        <el-option label="创建时间" value="create_time" />
        <el-option label="评论数量" value="comment_num" />
        <el-option label="点赞数量" value="like_num" />
        <el-option label="浏览量" value="view_num" />
      </el-select>
      <el-select v-model="orderBy" placeholder="排序方式" @change="handleFilterChange">
        <el-option label="升序" value="asc" />
        <el-option label="降序" value="desc" />
      </el-select>
    </div>

    <el-empty v-if="discussions.length === 0" description="暂无讨论" />

    <div v-else class="discussion-list">
      <div v-for="discussion in discussions" :key="discussion.id" class="discussion-item" @click="goToDiscussionDetail(discussion.id)">
        <div class="discussion-info">
          <div class="user-info">
            <el-avatar :src="discussion.avatar ? discussion.avatar : defaultAvatar" :size="40"></el-avatar>
            <div class="author-info">
              <span class="author-name">{{ discussion.author }}</span>
              <span class="role-tag" v-if="discussion.role === 1">教师</span>
              <span class="role-tag" v-else-if="discussion.role === 2">管理员</span>
              <span class="create-time">{{ formatTime(discussion.createTime) }}</span>
            </div>
          </div>
          <h2 class="discussion-title">{{ discussion.title }}</h2>
          <p class="discussion-content">{{ discussion.content }}</p>
        </div>
        <div class="discussion-stats">
          <div class="stat-item">
            <el-icon><View /></el-icon>
            <span>{{ discussion.viewNum || 0 }}</span>
          </div>
          <div class="stat-item">
            <el-icon><ChatLineRound /></el-icon>
            <span>{{ discussion.commentNum || 0 }}</span>
          </div>
          <div class="stat-item">
            <el-icon><StarFilled /></el-icon>
            <span>{{ discussion.likeNum || 0 }}</span>
          </div>
        </div>
      </div>
    </div>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '../store/user';
import { ElMessage } from 'element-plus';
import { View, ChatLineRound, StarFilled } from '@element-plus/icons-vue';
import { fetchDiscussionList } from '../api/discussion';

// 使用URL替代本地图片导入
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

const router = useRouter();
const userStore = useUserStore();

// 检查用户是否登录
const isLoggedIn = computed(() => userStore.isLoggedIn);

// 讨论列表数据
const discussions = ref<any[]>([]);
const total = ref(0);
const loading = ref(false);

// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);

// 排序参数
const sortBy = ref('create_time');
const orderBy = ref('desc');

// 获取讨论列表
const getDiscussions = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      sortBy: sortBy.value,
      orderBy: orderBy.value
    };
    
    const result = await fetchDiscussionList(params);
    if (result && result.code === 0) {
      discussions.value = result.data.records || [];
      total.value = result.data.total || 0;
    } else {
      ElMessage.error(result?.msg || '获取讨论列表失败');
    }
  } catch (error) {
    console.error('获取讨论列表失败:', error);
    ElMessage.error('获取讨论列表失败');
  } finally {
    loading.value = false;
  }
};

// 处理排序变化
const handleFilterChange = () => {
  currentPage.value = 1; // 重置到第一页
  getDiscussions();
};

// 处理页面大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getDiscussions();
};

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getDiscussions();
};

// 跳转到讨论详情页
const goToDiscussionDetail = (id: number) => {
  router.push(`/discussion/${id}`);
};

// 跳转到创建讨论页
const goToCreateDiscussion = () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }
  router.push('/discussion/create');
};

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return '';
  const date = new Date(time);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 组件挂载时获取讨论列表
onMounted(() => {
  getDiscussions();
});
</script>

<style scoped>
.discussion-list-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.discussion-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.discussion-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.filter-options {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.discussion-list {
  margin-top: 20px;
}

.discussion-item {
  display: flex;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 15px;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.discussion-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
}

.discussion-info {
  flex: 1;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.author-info {
  margin-left: 10px;
  display: flex;
  flex-direction: column;
}

.author-name {
  font-weight: 600;
  color: #303133;
}

.role-tag {
  background-color: #409eff;
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  margin-left: 8px;
}

.create-time {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.discussion-title {
  margin: 0 0 10px 0;
  font-size: 18px;
  color: #303133;
  word-break: break-all;
}

.discussion-content {
  color: #606266;
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.discussion-stats {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  padding-left: 20px;
  border-left: 1px solid #ebeef5;
  min-width: 100px;
}

.stat-item {
  display: flex;
  align-items: center;
  color: #909399;
}

.stat-item .el-icon {
  margin-right: 5px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 